package com.jiusit.golf.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LotteryUtil {
	public static String getLotteryData(String dateStr,String periodStr) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL newUrl = new URL(
					"http://caipiao.163.com/award/cqssc/"+dateStr+".html");
			/*URL newUrl = new URL(
					"http://www.baidu.com");*/
			HttpURLConnection hConnect = (HttpURLConnection) newUrl
					.openConnection();
			// POST方式的额外数据
			hConnect.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(
					hConnect.getOutputStream());
			out.write("");
			out.flush();
			out.close();
			// 读取内容

			BufferedReader rd = new BufferedReader(new InputStreamReader(
					hConnect.getInputStream()));
			int ch;
			String line = "";
			while ((line = rd.readLine()) != null) {
				buffer.append(line);
	             } 
			
			String s = buffer.toString();
			System.out.println("中奖号码:"+s);
			String data="data-period=\""+periodStr+"\"";
			int index = buffer.indexOf(data) - 50;
			s = buffer.substring(index, index + 90);
			Pattern pattern = Pattern
					.compile("<td[^>]+data-win-number\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
			Matcher matcher = pattern.matcher(s);
			while (matcher.find()) {
				s=matcher.group(1);
				s=s.replaceAll(" ", "");
				System.out.println("中奖号码:"+matcher.group(1));
			}
			rd.close();
			hConnect.disconnect();
			return s;
		} catch (Exception e) {
			return "";
		}
	}
}
